<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">自然语言转SQL查询</h1>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div class="lg:col-span-2">
        <QueryInput @query-submitted="handleQuery" />
        <div v-if="sql" class="mt-6 bg-white p-6 rounded-lg shadow">
          <h2 class="text-lg font-semibold mb-4">生成的SQL</h2>
          <pre class="bg-gray-50 p-4 rounded text-sm">{{ sql }}</pre>
        </div>
        <ResultTable class="mt-6" :data="queryResult" :loading="loading" />
      </div>
      <div>
        <QueryHistory @select-history="handleHistorySelect" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import QueryInput from '../components/QueryInput.vue'
import QueryHistory from '../components/QueryHistory.vue'
import ResultTable from '../components/ResultTable.vue'
import { nl2sql } from '../services/api'
import { storage } from '../utils/storage'
import { ElMessage } from 'element-plus'

const queryResult = ref([])
const sql = ref('')
const loading = ref(false)

const handleQuery = async (query) => {
  loading.value = true
  try {
    // 发送查询请求
    const response = await nl2sql.query(query)
    
    // 检查响应状态
    if (!response.data.success) {
      throw new Error(response.data.msg || '查询失败')
    }

    // 更新查询结果
    if (response.data.data) {
      queryResult.value = Array.isArray(response.data.data) ? response.data.data : []
    }

    // 保存到历史记录
    storage.saveHistory({
      query,
      sql: sql.value,
      timestamp: Date.now()
    })

    ElMessage.success(response.data.msg || '查询成功')
  } catch (error) {
    console.error('查询出错:', error)
    let errorMessage = '查询失败'
    if (error.response) {
      // 服务器返回错误
      errorMessage = error.response.data?.msg || `服务器错误 (${error.response.status})`
    } else if (error.request) {
      // 请求发送失败
      errorMessage = '无法连接到服务器，请检查网络连接'
    } else {
      // 其他错误
      errorMessage = error.message || '发生未知错误'
    }
    ElMessage.error(errorMessage)
    sql.value = ''
    queryResult.value = []
    throw error // 重新抛出错误以通知调用者
  } finally {
    loading.value = false
  }
}

const handleHistorySelect = async (historyItem) => {
  sql.value = historyItem.sql
  await handleQuery(historyItem.query)
}
</script> 